<?php
namespace app\task\model;
use app\common\model\Recharge as RechargeModel;
use app\common\model\User as UserModel;
use think\Db;

/**
 * 用户充值模型
 */
class Recharge extends RechargeModel
{
    /**
     * 待支付订单详情
     */
    public function payDetail($order_no)
    {
        return self::get(['order_no' => $order_no]);
    }

    /**
     * 更新付款状态
     */
    public function updatePayStatus($transaction_id)
    {
		//避免重复回调
		if($this['transaction_id']){
			return false;
		}
		// 开启事务
        Db::startTrans();
		//获取用户详情
		$user = UserModel::getUser(['user_id' => $this->user_id]);
		/*
		$unionid = $user['union_id'];
		//支付后获取用户 Unionid
		$result = getUnionid($user['wxapp_id'],$user['open_id'],$transaction_id);
		if($result){
			$unionid = $result;
		}
		$user->union_id = $unionid;
		*/
		$wallet = $this->money + $this->gift_money; //充值金额+赠送金额
		$user->wallet = ['inc', $wallet];//增加充值金额
		$user->score = ['inc', $this->money];//增加积分
		$user->save();
		/*
		//发送模板消息 - 使用公众号
		if($unionid){
			//判断是否关注公众号
			if($wxuser = UserModel::getUser(['union_id' => $unionid,'type' => 20])){
				//判断是否配置了模板消息
				$tmsg = SettingModel::getItem('tmsg',$wxuser['wxapp_id']);
				if($tmsg['recharge']['template_id']){
					$tmsg['recharge']['touser'] = $wxuser['open_id'];
					$tmsg['recharge']['data']['keyword1']['value'] = $order['money'].'元';
					$tmsg['recharge']['data']['keyword2']['value'] = date('Y-m-d H:i:s',time());
					$tmsg['recharge']['data']['keyword3']['value'] = $user->wallet .'元';
					f_msg($tmsg['recharge'],$wxuser['wxapp_id']); //发送模板消息
				}
			}	
		}*/
		// 更新订单状态
		$this->save([
			'pay_status' => 20,
			'pay_time' => time(),
			'transaction_id' => $transaction_id,
		]);
		Db::commit();
        return true;
    }

}
